package com.wang.spring.handler;

import com.alibaba.fastjson.JSONObject;
import com.wang.just_sql.JustSql;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JustSqlHandler extends HandlerInterceptorAdapter implements InitializingBean {
    private DataSource dataSource;

    public JustSqlHandler(DataSource dataSource) throws IOException {
        this.dataSource = dataSource;
        JustSql.InitDatabase(dataSource, justSqlConfigFile);
    }

    private File justSqlConfigFile = new File("./src/main/resource/just_sql/sql.xml.vm");

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getServletPath();
        if(!JustSql.contains(url)) {
            return super.preHandle(request, response, handler);
        }
        Map<String, Object> param = new HashMap<>();
        int length = request.getContentLength();
        if(length != -1) {
            byte[] bs = new byte[length];
            request.getInputStream().read(bs, 0, length);
            param = JSONObject.parseObject(new String(bs)).getInnerMap();
        }
        List<Map<String, Object>> result = JustSql.execute(url, param);
        response.getWriter().write(JSONObject.toJSONString(result));
        return false;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        JustSql.InitDatabase(dataSource, justSqlConfigFile);
    }
}
